package com.yidao.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.yidao.user.service.AuthenticationException;
import com.yidao.user.service.UserService;

@Controller
public class Login {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login/new.do")
    public ModelAndView loginForm() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/login/login_form");
        return mav;
    }
	
    public ModelAndView login(	
    							@RequestParam("username") String username,
    							@RequestParam("password") String password
    							) {
		
		try {
			userService.authenticate(username, password);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			ModelAndView mav = new ModelAndView();
			mav.addObject("message", "Invalide username and password");
			mav.setViewName("login/login_form");
			return mav;
		}
		
		ModelAndView main = new ModelAndView();
		main.setViewName("main");
		return main;
    }
}
